package edu.tyut.lingyunxing.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import edu.tyut.lingyunxing.common.Constant;
import edu.tyut.lingyunxing.common.R;
import edu.tyut.lingyunxing.dto.TicketBuyDTO;
import edu.tyut.lingyunxing.dto.TicketDTO;
import edu.tyut.lingyunxing.pojo.Airport;
import edu.tyut.lingyunxing.pojo.Flight;
import edu.tyut.lingyunxing.pojo.Ticket;
import edu.tyut.lingyunxing.service.AirportService;
import edu.tyut.lingyunxing.service.FlightService;
import edu.tyut.lingyunxing.service.TicketService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * DateTime: 2025/6/25 - 13:38
 * Author: Ycs
 */
@RestController
@RequestMapping("/ticket")
@Slf4j
public class TicketController {

    @Resource
    private TicketService service;

    @Resource
    private FlightService flightService;
    
    @Resource
    private AirportService airportService;

    @PostMapping("/buy")
    public R<String> buy(@RequestBody TicketBuyDTO dto, HttpServletRequest request) {
        Long userId = (Long) request.getSession().getAttribute(Constant.SESSION_USER_KEY);
        Flight flight = flightService.getById(dto.getFlightId());
        // 获取机上顺位座位
        Long seat = computeSeat(dto.getSeatType(), flight);
        Ticket ticket = Ticket.builder()
                .user(userId)
                .flight(dto.getFlightId())
                .seatType(dto.getSeatType())
                .seat(seat)
                .build();
        boolean b = service.save(ticket);
        return b ? R.success("购票成功") : R.error("购票失败！");
    }
    
    @PostMapping("/refund")
    public R<String> refund(@RequestBody RefundDTO dto, HttpServletRequest request) {
        boolean b = service.removeById(dto.getTicketId());
        return b ? R.success("退票成功") : R.error("退票失败");
    }
    
    @GetMapping("/list")
    public R<List<TicketDTO>> list(HttpServletRequest request) {
        Long userId = (Long) request.getSession().getAttribute(Constant.SESSION_USER_KEY);
        if (userId == null) {
            return R.error("未登录");
        }
        LambdaQueryWrapper<Ticket> q = new LambdaQueryWrapper<>();
        q.eq(Ticket::getUser, userId);
        List<Ticket> list = service.list(q);
        List<TicketDTO> res = new ArrayList<>();
        for (Ticket ticket : list) {
            Long flightId = ticket.getFlight();
            Flight flight = flightService.getById(flightId);

            Airport from = airportService.getById(flight.getFromAirport());
            Airport to = airportService.getById(flight.getToAirport());

            TicketDTO dto = TicketDTO.builder()
                    .id(ticket.getId())
                    .from(from.getName())
                    .to(to.getName())
                    .flyTime(flight.getFlyTime())
                    .endTime(flight.getEndTime())
                    .seatType(ticket.getSeatType())
                    .seat(ticket.getSeat() + "号")
                    .build();
            res.add(dto);
        }
        return R.success(res);
    }
    
    private Long computeSeat(Integer seatType, Flight flight) {
        // 注意这里的座位是分开算的，经济舱和商务舱是分开算的
        if (seatType == 1) {
            LambdaQueryWrapper<Ticket> q = new LambdaQueryWrapper<>();
            q.eq(Ticket::getFlight, flight.getId())
                    .eq(Ticket::getSeatType, 1);
            List<Ticket> economy = service.list(q);
            int size = economy.size() + 1;
            return (long) size;
        } else {
            // 经济舱
            LambdaQueryWrapper<Ticket> qb = new LambdaQueryWrapper<>();
            qb.eq(Ticket::getFlight, flight.getId())
                    .eq(Ticket::getSeatType, 0);
            List<Ticket> economy = service.list(qb);
            int size = economy.size() + 1;
            return (long) size;
        }
    }

}
